<?php

use think\Db;

/**
 * 字符串截取，支持中文和其他编码
 */
function msubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = true)
{
    if(function_exists("mb_substr")){
        $slice = mb_substr($str, $start, $length, $charset);
    }else{
        if(function_exists('iconv_substr')){
            $slice = iconv_substr($str, $start, $length, $charset);
            if(false === $slice){
                $slice = '';
            }
        }else{
            $re['utf-8']  = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
            $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
            $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
            $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
            preg_match_all($re[$charset], $str, $match);
            $slice = join("", array_slice($match[0], $start, $length));
        }
    }
    return $suffix ? $slice . '...' : $slice;
}

/**
 * 读取配置
 *
 * @return array
 */
function load_config()
{
    $list   = Db::name('config')->select();
    $config = [];
    foreach($list as $k => $v){
        $config[trim($v['name'])] = $v['value'];
    }
    return $config;
}

/**
 * 验证手机号是否正确
 *
 * @author honfei
 *
 * @param number $mobile
 */
function isMobile($mobile)
{
    if(!is_numeric($mobile)){
        return false;
    }
    return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
}

//生成网址的二维码 返回图片地址
function Qrcode($token, $url, $size = 8)
{
    $md5   = md5($token);
    $dir   = date('Ymd') . '/' . substr($md5, 0, 10) . '/';
    $patch = 'qrcode/' . $dir;
    if(!file_exists($patch)){
        mkdir($patch, 0755, true);
    }
    $file     = 'qrcode/' . $dir . $md5 . '.png';
    $fileName = $file;
    if(!file_exists($fileName)){

        $level = 'L';
        $data  = $url;
        QRcode::png($data, $fileName, $level, $size, 2, true);
    }
    return $file;
}

/**
 * 循环删除目录和文件
 *
 * @param string $dir_name
 *
 * @return bool
 */
function delete_dir_file($dir_name)
{
    $result = false;
    if(is_dir($dir_name)){
        if($handle = opendir($dir_name)){
            while(false !== ($item = readdir($handle))){
                if($item != '.' && $item != '..'){
                    if(is_dir($dir_name . DS . $item)){
                        delete_dir_file($dir_name . DS . $item);
                    }else{
                        unlink($dir_name . DS . $item);
                    }
                }
            }
            closedir($handle);
            if(rmdir($dir_name)){
                $result = true;
            }
        }
    }
    return $result;
}

//时间格式化1
function formatTime($time)
{
    $now_time = time();
    $t        = $now_time - $time;
    $mon      = (int)($t / (86400 * 30));
    if($mon >= 1){
        return '一个月前';
    }
    $day = (int)($t / 86400);
    if($day >= 1){
        return $day . '天前';
    }
    $h = (int)($t / 3600);
    if($h >= 1){
        return $h . '小时前';
    }
    $min = (int)($t / 60);
    if($min >= 1){
        return $min . '分钟前';
    }
    return '刚刚';
}

//时间格式化2
function pincheTime($time)
{
    $today = strtotime(date('Y-m-d')); //今天零点
    $here  = (int)(($time - $today) / 86400);
    if($here == 1){
        return '明天';
    }
    if($here == 2){
        return '后天';
    }
    if($here >= 3 && $here < 7){
        return $here . '天后';
    }
    if($here >= 7 && $here < 30){
        return '一周后';
    }
    if($here >= 30 && $here < 365){
        return '一个月后';
    }
    if($here >= 365){
        $r = (int)($here / 365) . '年后';
        return $r;
    }
    return '今天';
}

function getRandomString($len, $chars = null)
{
    if(is_null($chars)){
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    }
    mt_srand(10000000 * (double)microtime());
    for($i = 0, $str = '', $lc = strlen($chars) - 1; $i < $len; $i++){
        $str .= $chars[mt_rand(0, $lc)];
    }
    return $str;
}

if(!function_exists('random_str')){
    /**
     * 获取随机字符串
     *
     * @param $length
     *
     * @return string
     * @author   [小码哥]
     */
    function random_str($length)
    {
        //生成一个包含 大写英文字母, 小写英文字母, 数字 的数组
        $arr     = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'));
        $str     = '';
        $arr_len = count($arr);
        for($i = 0; $i < $length; $i++){
            $rand = mt_rand(0, $arr_len - 1);
            $str  .= $arr[$rand];
        }
        return $str;
    }
}



if(!function_exists('get_position_ad')){
    /**
     * 根据广告位获取广告
     *
     * @param int $position_id
     *
     * @return false|PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author   [小码哥]
     */
    function get_position_ad($position_id = 1)
    {
        $list = Db::name('Ad')->where('ad_position_id', $position_id)->select();
        foreach($list as $index => $item){
            $item['images'] = str_replace('\\', '/', $item['images']);
            $list[$index]   = $item;
        }
        return $list;
    }
}


if(!function_exists('friend_date')){

    function friend_date($time)
    {
        if(!$time){
            return false;
        }
        $d  = time() - intval($time);
        $ld = $time - mktime(0, 0, 0, 0, 0, date('Y')); //得出年
        $dd = $time - mktime(0, 0, 0, date('m'), date('d'), date('Y')); //今天
        if($d == 0){
            $FDate = '刚刚';
        }else{
            switch($d){
                case $d < 60:
                    $FDate = $d . '秒前';
                    break;
                case $d < $dd:
                    $FDate = date('H:i', $time);
                    break;
                case $d < $ld:
                    $FDate = date('m月d日 H:i', $time);
                    break;
                default:
                    $FDate = date('Y年m月d日 H:i', $time);
                    break;
            }
        }
        return $FDate;
    }
}
if(!function_exists('hide_card')){
    /**
     * 隐藏指定位数
     *
     * @param     $card
     * @param int $startNum
     * @param int $endNum
     *
     * @return bool|string
     * @author   [小码哥]
     */
    function hide_card($card, $startNum = 4, $endNum = 4)
    {
        if(!$card){
            return false;
        }
        $length = strlen($card);
        $string = substr($card, 0, $startNum);
        $xin    = $length - ($startNum + $endNum);
        for($i = 0; $i < $xin; $i++){
            $string .= '*';
        }
        $string .= substr($card, -$endNum);
        return $string;
    }
}
if(!function_exists('get_nickname')){
    /**
     * 获取名字
     *
     * @param $account
     *
     * @return mixed
     * @author   [小码哥]
     */
    function get_nickname($account)
    {
        return Db::name('Member')->where('account', $account)->value('nickname');
    }
}
if(!function_exists('get_tui_num')){
    /**
     * 获取推荐数量
     *
     * @param $account
     *
     * @return mixed
     * @author   [小码哥]
     */
    function get_tui_num($account)
    {
        return Db::name('Member')->where('rec_id', $account)->count();
    }
}
if(!function_exists('get_zi_ge')){
    /**
     * 获取资格所属
     *
     * @param $account
     *
     * @return mixed
     * @author   [小码哥]
     */
    function get_zi_ge($account)
    {
        return Db::name('Group')->where(['gua1|gua2' => $account])->value('account');
    }
}
if(!function_exists('isController')){
    /**
     * 判断当前控制器和方法
     *
     * @param string $controller
     *
     * @return string
     * @author   [小码哥]
     */
    function isController($controller = 'index/index')
    {
        if(strtolower(request()->controller() . '/' . request()->action()) == strtolower($controller)){
            return 'active';
        }else{
            return '';
        }
    }
}
if(!function_exists('get_ad')){
    /**
     * 获取广告
     *
     * @param int $ad_position
     *
     * @return false|PDOStatement|string|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author   [小码哥]
     */
    function get_ad($ad_position = 0)
    {
        return Db::name('Ad')
            ->where([
                'ad_position_id' => $ad_position,
                'start_date'     => ['<=', time()],
                'end_date'       => ['>', time()],
                'status'         => 1
            ])
            ->order(['orderby' => 'ASC'])
            ->select();
    }
}
if(!function_exists('kuai_di')){
    /**
     * 快递代码
     *
     * @return array
     * @author   [小码哥]
     */
    function kuai_di()
    {
        $code = [
            ['name' => '韵达快运', 'type' => 'yunda', 'status' => 1],
            ['name' => '顺丰快递', 'type' => 'shunfeng', 'status' => 1],
            ['name' => '申通快递', 'type' => 'shentong', 'status' => 1],
            ['name' => '中通速递', 'type' => 'zhongtong', 'status' => 1],
            ['name' => '圆通速递', 'type' => 'yuantong', 'status' => 1],
            ['name' => '天天快递', 'type' => 'tiantian', 'status' => 1],
            ['name' => '百世汇通', 'type' => 'huitongkuaidi', 'status' => 1],
            ['name' => 'EMS', 'type' => 'ems', 'status' => 1],
            ['name' => '邮政小包', 'type' => 'youzhengguonei', 'status' => 1],
        ];
        return $code;
    }
}
function get_kuai_di($status = 0)
{
    $path = ROOT_PATH . 'application' . DS . 'common' . DS . 'code.json';
    $json = file_get_contents(str_replace('\\', '/', $path));
    $json = json_decode($json, true);
    if($status == 1){
        foreach($json as $key => $value){
            if($value['status'] == 1){
                $json[$key] = $value;
            }
        }
    }
    return $json;
}

function set_kuai_di($param)
{
    $path = ROOT_PATH . 'application' . DS . 'common' . DS . 'code.json';
    return file_put_contents(str_replace('\\', '/', $path), json_encode($param));
}

/**
 * 设置获取商城设置
 *
 * @param string $type
 * @param string $filename
 * @param array  $param
 *
 * @return bool|int|mixed
 * @author   [小码哥]
 */
function get_or_set_shop($type = 'get', $filename = 'shop', $param = [])
{
    $filename = strtolower($filename);
    if($type == 'get'){
        $path = ROOT_PATH . 'application' . DS . 'common' . DS . "{$filename}.json";
        $json = file_get_contents(str_replace('\\', '/', $path));
        return json_decode($json, true);
    }else{
        if(!empty($param)){
            $path = ROOT_PATH . 'application' . DS . 'common' . DS . "{$filename}.json";
            return file_put_contents(str_replace('\\', '/', $path), json_encode($param));
        }
    }
    return false;
}

function get_price($price = '0.00', $index = 0)
{
    $price = explode('.', $price);
    return $price[$index];
}

//获取当前用户的手续费综合
//$percentage 总和的分润比例
function shouxu_money($user_id,$percentage){
    $re = \app\admin\model\TransactionRecord::where('user_id',$user_id)->select();
    //综合
    $num = 0;
    if($re){
        foreach($re as $v){
            $num+=(int)$v['service_money'];
        }
    }
    $lirun =  number_format($num*$percentage, 2); //10.46
    return $lirun;
}
//金额操作日志
function money_log($title,$content,$member_id,$ter_id =0,$old='',$new='',$type=null,$money=0){
    Db::table('think_money_log')->insert([
        'title'=>$title,
        'content'=>$content,
        'member_id'=>$member_id,
        'ter_id'=>$ter_id,
        'old'=>$old,
        'new'=>$new,
        'type'=>$type,
        'money' => $money,
        'created_at'=>time()
    ]);
}
/*
   * 意见反馈  类型
   *
   * */
function feedback_type(){
    return [
        1=>'类型1',
        2=>'类型2',
        3=>'类型3'
    ];
}

